/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.store;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Comparator;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.Validate;

import ru.irenproject.BadInputException;
import ru.irenproject.Check;

import com.google.common.primitives.UnsignedBytes;
import com.google.protobuf.ByteString;

public final class Ids {
  public static final int SIZE = 16;

  public static final ByteString ZERO = fromBytes(new byte[SIZE]);

  public static final Comparator<ByteString> COMPARATOR = new IdComparator();

  public static ByteString fromBytes(byte[] value) {
    Validate.isTrue(value.length == SIZE);
    return ByteString.copyFrom(value);
  }

  public static ByteString fromAlienHexString(String s) {
    Check.inputNotNull(s);

    byte[] ba;
    try {
      ba = Hex.decodeHex(s.toCharArray());
    } catch (DecoderException e) {
      throw new BadInputException(e);
    }

    Check.input(ba.length == SIZE);
    return fromBytes(ba);
  }

  public static String toHexString(ByteString id) {
    checkValid(id);
    return Hex.encodeHexString(id.toByteArray());
  }

  public static boolean valid(ByteString id) {
    return id.size() == SIZE;
  }

  public static void checkValid(ByteString id) {
    Validate.isTrue(valid(id));
  }

  public static ByteString read(DataInput in) {
    try {
      byte[] ba = new byte[SIZE];
      in.readFully(ba);
      return fromBytes(ba);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static void write(ByteString id, DataOutput out) {
    checkValid(id);

    try {
      out.write(id.toByteArray());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static final class IdComparator implements Comparator<ByteString> {
    @Override public int compare(ByteString left, ByteString right) {
      checkValid(left);
      checkValid(right);

      for (int i = 0; i < SIZE; ++i) {
        int d = UnsignedBytes.compare(left.byteAt(i), right.byteAt(i));
        if (d != 0) {
          return d;
        }
      }
      return 0;
    }
  }

  private Ids() {}
}
